package com.ieng.ormosia.groups.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextListener;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.*;

@Configuration
public class ServerConfig {

    @Bean("webCorsFilter")
    public CorsFilter corsFilter(){
        List<String> allowedHeaders = Arrays.asList("Content-Type", "X-Requested-With", "XMLHttpRequest");
        List<String> allowedMethods = Arrays.asList("POST", "GET", "PUT", "DELETE", "OPTIONS");
        List<String> allowedOrigins = Collections.singletonList("*");

        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.setAllowedHeaders(allowedHeaders);
        corsConfiguration.setAllowedMethods(allowedMethods);
        corsConfiguration.setAllowedOrigins(allowedOrigins);

        Map<String, CorsConfiguration> configurationMap = new LinkedHashMap<>();
        configurationMap.put("/**", corsConfiguration);

        UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource();
        configurationSource.setCorsConfigurations(configurationMap);
        return new CorsFilter(configurationSource);
    }

    @Bean
    public RequestContextListener requestContextListener(){
        return new RequestContextListener();
    }

}
